/**
 * 
 */
package edu.gatech.oad.yuno;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.*;

/**
 * This activity is responsible for handling password resets. Note: Not a project requirement.
 * @author Melaena
 *
 */
public class ForgotPasswordActivity extends Activity implements View.OnClickListener {
	
	private Button resetPassword;
	private TextView enterUsername;
	private EditText username;
	
	/**
	 * Establishes variables from the elements of the xml layout
	 * 
	 * @param savedInstanceState
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState == null || 
				!savedInstanceState.getBoolean("loggedIn", false)) {
			//set up login screen
			setContentView(R.layout.forgot_password);
			enterUsername = (TextView) findViewById(R.id.enterUsername);
			username = (EditText) findViewById(R.id.username);
			resetPassword = (Button) findViewById(R.id.resetPassword);
			
			resetPassword.setOnClickListener(this);
		} else {
			//set up main screen
			setContentView(R.layout.main);
		}
	}

	/**
	 * Listener for the reset password button. SHows error if the username doesn't exist.
	 * 
	 * @param v
	 * 		reset password button
	 */
	public void onClick(View v) {
		if (v == resetPassword) {
			if (User.find(username.getText().toString())==null){
				//NEED FOR THIS TO CHECK ALL THE EXISTING USERNAMES
				Toast.makeText(this, "Invalid username.",
	    				Toast.LENGTH_SHORT).show();
			}
			else if(username.getText().toString().trim().length()==0){ //checks length of what they entered, excluding whitespace (trim())
				Toast.makeText(getApplicationContext(), "Nice try, but we need your username.",
						Toast.LENGTH_SHORT).show();
			}
			else{
				//Need to add sending e-mail to the e-mail corresponding to the username they input.
				//NEED TO ADD THAT FUNCTIONALITY IN
				Intent intent = new Intent(this, YUNoDosActivity.class);
				startActivity(intent);
				User user = User.find(username.getText().toString());
				
				try{
					EMailSender sender = new EMailSender("yunodosender@gmail.com", "yunodo2340");
					//user.setPassword(user.resetPassword());
					sender.sendMail("You forgot your password...", "Your password is " + user.getPassword(), "yunodosender@gmail.com", user.getEmail());
					Toast.makeText(this, "Email sent.", Toast.LENGTH_SHORT).show();
				}
				catch(Exception e){
					Log.e("SendMail", e.getMessage(), e);
				}
				
			}
		}
	}
}
